package cn.bluethink.graphical;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;

import cn.bluethink.view.Graph;

public class Line extends Graph {

	private Point mFromPoint = new Point(0,0);
	private Point mToPoint = new Point(0,0);
		
	public Line(){
		
	}
	
	public Line(Point from, Point to){
		if(from != null) {
			mFromPoint.setLocation(from.getX(), from.getY());
		}
		if(to != null) {
			mToPoint.setLocation(to.getX(), to.getY());
		}
	}
	
	public Point getFromPoint() {
		return mFromPoint;
	}
	
	public Point getToPoint() {
		return mToPoint;
	}
	@Override
	public String type() {
		return "line";
	}

	@Override
	public int getHandleCount() {
		return 2;
	}

	@Override
	public Point getHandle(int index) {
		if( index == 0 ) return mFromPoint;
		else if ( index == 1 ) return mToPoint;
		else return new Point(0,0);
	}

	@Override
	public void draw(Graphics c) {
		Color oldColor= c.getColor();
		c.setColor(mColor);

		c.drawLine((int)mFromPoint.getX(), (int)mFromPoint.getY(), (int)mToPoint.getX(), (int)mToPoint.getY());
		c.setColor(oldColor);
	}

	@Override
	public int hitTest(Point pt) {
		
		if( Math.abs(pt.getX()-mFromPoint.getX()) <= SEL_TOLERANCE && Math.abs(pt.getY()-mFromPoint.getY()) <= SEL_TOLERANCE )
			return 1;
		else if ( Math.abs(pt.getX()-mToPoint.getX()) <= SEL_TOLERANCE && Math.abs(pt.getY()-mToPoint.getY()) <= SEL_TOLERANCE )
			return 2;
		else if ( pt.getX() >= (mFromPoint.getX() > mToPoint.getX() ? mToPoint.getX() : mFromPoint.getX()) &&
			      pt.getX() <= (mFromPoint.getX() < mToPoint.getX() ? mToPoint.getX() : mFromPoint.getX()) &&
				  pt.getY() >= (mFromPoint.getY() > mToPoint.getY() ? mToPoint.getY() : mFromPoint.getY()) &&
			      pt.getY() <= (mFromPoint.getY() < mToPoint.getY() ? mToPoint.getY() : mFromPoint.getY()) )//点到直线距离算法
			return -1;
		return 0;
	}

	@Override
	public void moveTo(int dx, int dy) {
		mFromPoint.translate(dx,dy);
		mToPoint.translate(dx,dy);
	}

	@Override
	public void moveHandleTo(int handleIndex, Point pt) {
		if(pt == null) {
			return;
		}
		if ( handleIndex == 1 )
			mFromPoint.setLocation(pt.getX(), pt.getY());
		else if ( handleIndex == 2 )
			mToPoint.setLocation(pt.getX(), pt.getY());
	}

	@Override
	public void drawAsSelect(Graphics c) {
		Color oldColor= c.getColor();
		c.setColor(Color.YELLOW);

		c.drawLine((int)mFromPoint.getX(), (int)mFromPoint.getY(), (int)mToPoint.getX(), (int)mToPoint.getY());
		c.setColor(oldColor);
	}

	public Point getmFromPoint() {
		return mFromPoint;
	}

	public void setmFromPoint(Point mFromPoint) {
		this.mFromPoint = mFromPoint;
	}

	public Point getmToPoint() {
		return mToPoint;
	}

	public void setmToPoint(Point mToPoint) {
		this.mToPoint = mToPoint;
	}
}
